/**
 * 
 */
package com.zznode.client.wlanpolling.test;

import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import junit.framework.Test;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.farproc.wifi.connecter.NewNetworkContent;
import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.model.TestResult;
import com.zznode.client.wlanpolling.model.TestResultConstants;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.service.NetworkProber;
import com.zznode.client.wlanpolling.utils.IMessageUpdater;
import com.zznode.client.wlanpolling.utils.NetworkUtils;
import com.zznode.client.wlanpolling.utils.PingTask;
import com.zznode.client.wlanpolling.utils.PingUtils;

/**
 * @author Jerome
 *
 */
public class CoverTestActivity extends Activity {
	private WifiManager mainWifi;
	private NetworkProber prober;
	private int currentIndex = -1;
	private Views[] views = new Views[4];
	private ProgressDialog pd;
	private WLANPollingApplication application;
	
	private IMessageUpdater[] all = new IMessageUpdater[3];
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (WLANPollingApplication)getApplication();
		
		ScrollView sv = new ScrollView(this);
		final LinearLayout root = new LinearLayout(this);
		root.setOrientation(LinearLayout.VERTICAL);
		root.setPadding(20, 10, 10, 0);
		root.setBackgroundResource(R.drawable.main_bg);
		populateUI(root);
		sv.addView(root);
		setContentView(sv);
		mainWifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

		prober = new NetworkProber(this);
		pd = new ProgressDialog(CoverTestActivity.this);
		
		new Handler().postDelayed(new Runnable(){
			public void run(){
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(root.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
			}
		}, 200);
	}
	
	protected void populateUI(ViewGroup root){
		TextView tv = new TextView(this);
		tv.setText("场点覆盖电平及信号质量测试：");
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		root.addView(tv, params);
		LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		for(int i = 0; i < 4; i++){
			View view = mInflater.inflate(R.layout.covertest, null);
			bindView(i, view);
			params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			root.addView(view, params);
		}
		final NumberFormat format = NumberFormat.getInstance();
		format.setMaximumFractionDigits(2);
//		receiverWifi = new BroadcastReceiver(){
//			public void onReceive(Context c, Intent intent) {
//				wifiList = mainWifi.getScanResults();
//				if(wifiList != null){
//					for(int i = 0; i < wifiList.size(); i++){
//						ScanResult sr = wifiList.get(i);
//						if(sr.BSSID.equals(bssid) && currentIndex >= 0 && currentIndex <views.length){
//							Views v = views[currentIndex];
//							int dp = sr.level + 100;
//							v.dianping.setText(dp + "dBm");
//							// 先计算功率
//							double p = Math.pow(10, dp / 10 - 3);
//							// 再计算相对于1W的dB值
//							// http://www.redwave.cc/server-view.asp?newsid=2
//							double db = Math.abs(10 * Math.log10(p));
//							v.xinzao.setText(format.format(db) + "dB");
//							break;
//						}
//					}
//				}
//			}
//		};
//		registerReceiver(receiverWifi, new IntentFilter(
//				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		Button btn = new Button(this);
		btn.setText("保存");
		btn.setTextSize(20);
		btn.setTextColor(Color.WHITE);
		btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				saveAction();
			}
			
		});
		btn.setBackgroundResource(R.drawable.btn_testsel);
		params = new LayoutParams(150, LayoutParams.WRAP_CONTENT);
		params.topMargin = 15;
		params.bottomMargin = 15;
		params.gravity = Gravity.CENTER_HORIZONTAL;
		root.addView(btn, params);
	}
	
	protected void bindView(final int index, View view){
		TextView tv = (TextView)view.findViewById(R.id.cover_loc);
		tv.setText("场点" + (index + 1));
		
		final TextView dianping = (TextView)view.findViewById(R.id.cover_dianping);
		final TextView xinzao = (TextView)view.findViewById(R.id.cover_xinzao);
		final TextView delay = (TextView)view.findViewById(R.id.cover_delay);
		final TextView lost = (TextView)view.findViewById(R.id.cover_lost);
		final TextView remark = (TextView)view.findViewById(R.id.cover_desc);
		
		Views v = new Views();
		v.delay = delay;
		v.dianping = dianping;
		v.lost = lost;
		v.xinzao = xinzao;
		v.remark = remark;
		
		TestResult result = WLANPollManager.getWLANPollManager().getTestResult();
		if(result != null) {
			String fieldname = "rssiremark" + (index+1);
			try {
				Field field = TestResult.class.getField(fieldname);
				Object value = field.get(result);
				if(value != null) {
					remark.setText(value.toString());
				} else {
					remark.setText("");
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
			
		}
		
		views[index] = v;
		
		Button test = (Button)view.findViewById(R.id.dotest);
		test.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				startTest(index);
			}
			
		});
	}
	
	private String replaceStr(String str1, String str2) {
		return str1.replace(str2, "");
	}
	private void startTest(int index){
		currentIndex = index;
		final Views vs = views[currentIndex];
//		mainWifi.startScan();
		String gateway = null;
		try {
			gateway = NetworkUtils.intToIp(prober.getDhcpInfo().gateway);
		} catch (Exception e) {
			gateway = "127.0.0.1";
		}
		pd.setTitle("测试");
		pd.setMessage("正在进行场点覆盖电平及信号质量测试，请稍候...");
		pd.show();
		all[0] = null; // no command window
		all[1] = new IMessageUpdater(){

			@Override
			public void messageUpdated(String message) {
				vs.delay.setText(message + "ms"); 
			}

			@Override
			public Context getContext() {
				return CoverTestActivity.this;
			}
			
		};
		all[2] = new IMessageUpdater(){

			@Override
			public void messageUpdated(String message) {
				vs.lost.setText(message + "%"); 
			}

			@Override
			public Context getContext() {
				return CoverTestActivity.this;
			}
			
		};
		new PingTask(all, pd).execute(new String[]{"-c 5", gateway});
		Views v = views[currentIndex];
		int dbm = mainWifi.getConnectionInfo().getRssi();
		int db = 100 + dbm;
		v.dianping.setText(dbm + "dBm");
		v.xinzao.setText(db + "dB");
	}
	
	private void saveAction(){
		String apMac = PingUtils.clearMacAdress(application.getContext().getCurrentWifi().getBSSID());

		Map<String, Object> values = new HashMap<String, Object>();
		
		Views v = views[0];
		values.put(TestResultConstants.DELAYVAL1, replaceStr(v.delay.getText().toString(), "ms"));
		values.put(TestResultConstants.PACKLOSTVAL1, v.lost.getText().toString());
		values.put(TestResultConstants.RSSIVAL1, replaceStr(v.dianping.getText().toString(), "dBm"));
		values.put(TestResultConstants.SNRVAL1, replaceStr(v.xinzao.getText().toString(), "dB"));
		values.put(TestResultConstants.RSSIREMARK1, v.remark.getText().toString());
		
		v = views[1];
		values.put(TestResultConstants.DELAYVAL2, replaceStr(v.delay.getText().toString(), "ms"));
		values.put(TestResultConstants.PACKLOSTVAL2, v.lost.getText().toString());
		values.put(TestResultConstants.RSSIVAL2, replaceStr(v.dianping.getText().toString(), "dBm"));
		values.put(TestResultConstants.SNRVAL2, replaceStr(v.xinzao.getText().toString(), "dB"));
		values.put(TestResultConstants.RSSIREMARK2, v.remark.getText().toString());
		
		v = views[2];
		values.put(TestResultConstants.DELAYVAL3, replaceStr(v.delay.getText().toString(), "ms"));
		values.put(TestResultConstants.PACKLOSTVAL3, v.lost.getText().toString());
		values.put(TestResultConstants.RSSIVAL3,replaceStr(v.dianping.getText().toString(), "dBm"));
		values.put(TestResultConstants.SNRVAL3, replaceStr(v.xinzao.getText().toString(), "dB"));
		values.put(TestResultConstants.RSSIREMARK3, v.remark.getText().toString());
		
		v = views[3];
		values.put(TestResultConstants.DELAYVAL4, replaceStr(v.delay.getText().toString(), "ms"));
		values.put(TestResultConstants.PACKLOSTVAL4, v.lost.getText().toString());
		values.put(TestResultConstants.RSSIVAL4, replaceStr(v.dianping.getText().toString(), "dBm"));
		values.put(TestResultConstants.SNRVAL4, replaceStr(v.xinzao.getText().toString(), "dB"));
		values.put(TestResultConstants.RSSIREMARK4, v.remark.getText().toString());
		values.put(TestResultConstants.SSID, application.getContext().getCurrentWifi().getSSID());
		
		WLANPollManager.getWLANPollManager().updateTestResult(application.getApplicationContext(), 
				apMac,
				values);
		
		Toast.makeText(this, "成功保存", Toast.LENGTH_SHORT).show();
		
	}
	
	@Override
	public void onBackPressed() {
//		unregisterReceiver(receiverWifi);
		super.onBackPressed();
	}

	class Views {
		public TextView dianping;
		public TextView xinzao;
		public TextView delay;
		public TextView lost;
		public TextView remark;
	}
	
	class testResults {
		public String dianping;
		public String xinzao;
		public String delay;
		public String lost;
	}
	
}
